package com.example.parkingproject.controller;


import com.example.parkingproject.config.aliyPay;
import com.example.parkingproject.jopo.entity.PayAsync;
import com.example.parkingproject.result.JsonResult;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/pay")
@AllArgsConstructor
@Slf4j
public class payController {


    @Autowired
    aliyPay aliyPay;

    @GetMapping(value = "/confirm", produces = {"text/html;charset=UTF-8"})
    public String confirm(String price) throws Exception {
        log.debug("停车支付{}",price);
        String pay = aliyPay.pay("停车收费" ,price);
        return pay;
    }

    @GetMapping(value = "/openVip", produces = {"text/html;charset=UTF-8"})
    public String openVip() throws Exception {
        String pay = aliyPay.pay("开通VIP","30");
        return pay;
    }

    @GetMapping(value = "/openMonth", produces = {"text/html;charset=UTF-8"})
    public String openMonth() throws Exception {
        String pay = aliyPay.pay("开通月租用户","300");
        return pay;
    }


    @PostMapping("/notify")
    @ResponseBody
    public String aliPayedNotify(HttpServletRequest request, PayAsync payAsync) {
        try {
            System.out.println("异步通知支付结果");
            //验签
            if (!aliyPay.signVerification(request.getParameterMap())) {
                return "fail";
            }

            //查看一下支付宝的回调信息
            System.out.println(payAsync);

            //如果是支付成功状态
            if ("TRADE_SUCCESS".equals(payAsync.getTrade_status()) || "TRADE_FINISHED".equals(payAsync.getTrade_status())) {
                //TODO 操作数据库修改订单状态。。这里省略

                return "success";
            }

            //如果是未付款交易超时关闭，或支付完成后全额退款
            if ("TRADE_CLOSED".equals(payAsync.getTrade_status())) {
                //TODO 操作数据库修改订单状态。。这里省略

                return "success";
            }
            return "fail";
        } catch (Exception e) {
            return "error";
        }
    }
}
